package com.jsg.sl651.entity.frame.header;

import com.jsg.sl651.enums.CommunicationMessageType;
import com.jsg.sl651.enums.MessageDirection;
import com.jsg.sl651.util.ByteUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class IdentificationAndLength {
    // 消息方向
    private final MessageDirection messageDirection;
    // 报文长度（报文起始符之后到报文结束符之前的报文长度）
    private final int length;

    public IdentificationAndLength(byte[] data) {
        if (data.length != 2) {
            throw new IllegalArgumentException("构建IdentificationAndLength的报文长度必须为2位");
        }
        int combined = (data[0] & 0xFF) << 8 | (data[1] & 0xFF);
        this.messageDirection = MessageDirection.getMessageDirection((combined >> 12) & 0x0F); // 右移12位，然后取低4位
        this.length = combined & 0x0FFF; // 取低12位
    }

    public byte[] toBodyBytes(CommunicationMessageType type) {
        if (type == CommunicationMessageType.HEX) {
            return getLength(messageDirection.getCode(), length);
        } else {
            String hex = ByteUtil.toHex(getLength(messageDirection.getCode(), length));
            return ByteUtil.stringToSimpleByteArray(hex);
        }
    }


    private byte[] getLength(int type,int length) {
        byte index1 = (byte) (((type & 0xff) << 4) | ((length & 0x0fff) >> 8));
        byte index2 = (byte) (length & 0xff);
        byte[] bytes = new byte[2];
        bytes[0] = index1;
        bytes[1] = index2;
        return bytes;
    }


}
